/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useReducer, Fragment } from "react";
import {
  Table,
  Avatar,
  Button,
  Form,
  Input,
  Modal,
  InputNumber,
  message,
} from "antd";
import { formatDate } from "../../util/tool";
import styles from "./index.module.scss";
import { getOrdersList, updateOrders } from "../../api/serve";
import { stati } from "../../api/api";
import { useForm } from "antd/es/form/Form";
import { connect } from "react-redux";
const initState = {
  orderData: "", //用户数据
  page: 1, //页码数
  total: "", //数据多少条
  key: "", //搜索key值
  skey: "", //触发搜索的条件，该值变化就进行搜索
  isOpen: false,
  count: 1,
  defauletpage: 1,
};

function adminRedcuer(state = initState, action) {
  if (action) {
    return { ...state, ...action };
  }
  return state;
}
function Order({ auth }) {
  const [state, dispatch] = useReducer(adminRedcuer, initState);
  const [form] = Form.useForm();
  const ORDER_MAP = {
    0: "未付款",
    1: "已付款",
    2: "已发货",
    3: "已收货",
    4: "已评价",
  };
  const handleisOpen = () => {
    dispatch({ isOpen: false });
  };
  const paginationProps = {
    //分页的配置
    defaultPageSize: 20,
    showSizeChanger: false,
    current: state.page,
    total: state.total,
    onChange: (page) => {
      //如果当前选择一页显示数据大于10条则将其恢复成最初状态
      dispatch({
        page,
      });
    },
  };
  const onSend = (record) => {
    dispatch({
      isOpen: true,
    });
    form.setFieldsValue({
      EMSname: "",
      status: "",
      EMS: "",
      orderid: "",
    });
  };
  const onFinish = (value) => {
    updateOrders({ ...value }, (res) => {
      message.success("发货成功");
      handleisOpen();
      init();
    });
  };
  const init = () => {
    //请求用户数据方法
    getOrdersList({ page: state.page }, (res) => {
      console.log(res);
      dispatch({
        orderData: res.data[0].data,
        total: res.data[1].data[0].count,
      });
    });
  };
  useEffect(
    // 监听state.page, state.pageSize, state.skey进行请求数据
    function () {
      init();
    },
    [state.page]
  );
  const columns = [
    {
      title: "订单号",
      dataIndex: "orderid",
      align: "center",
    },
    {
      title: "价格",
      dataIndex: "allprice",
      align: "center",
    },
    {
      title: "地址",
      dataIndex: "address",
      align: "center",
      render(data) {
        let dt = "";
        try {
          data = JSON.parse(data);
          dt = [data.name, data.tel, data.address];
        } catch (error) {
          dt = data;
        }
        // return [dt.name + dt.tel + dt.address].join(",");

        return dt;
      },
    },
    {
      title: "发货状态",
      dataIndex: "status",
      align: "center",
      render(data) {
        return ORDER_MAP[data];
      },
    },
    {
      title: "快递单号",
      dataIndex: "EMS",
      align: "center",
    },
    {
      title: "下单时间",
      dataIndex: "create_time",
      align: "center",
      render: (value) => {
        return formatDate(value, "YYYY-MM-DD hh:mm:ss");
      },
    },
    {
      title: "编辑",
      key: "action",
      align: "center",
      render: (_, record) => (
        <Fragment>
          {auth["/order"].update?.value && record.status === 1 && (
            <Button type="primary" onClick={() => onSend(record)}>
              发货
            </Button>
          )}
        </Fragment>
      ),
    },
  ];
  const expandedRowRender = (data) => {
    const columns = [
      {
        title: "id",
        dataIndex: "id",
        align: "center",
      },
      {
        title: "商品名称",
        dataIndex: "title",
        align: "center",
      },
      {
        title: "商品主图",
        dataIndex: "img",
        align: "center",
        render(data, record) {
          if (record.img) {
            return <img src={stati + data} alt="" style={{ width: "50px" }} />;
          }
          return <img src={data} alt="" style={{ width: "50px" }}></img>;
        },
      },
      {
        title: "颜色",
        dataIndex: "color",
        align: "center",
      },
      {
        title: "下单数量",
        dataIndex: "num",
        align: "center",
      },
      {
        title: "价格",
        dataIndex: "price",
        align: "center",
      },
    ];
    let dt = "";
    dt = JSON.parse(data.prolist);
    console.log(dt);
    return (
      <Fragment>
        <Table
          dataSource={dt}
          pagination={{ hideOnSinglePage: true }}
          rowKey="id"
          columns={columns}
        />
      </Fragment>
    );
  };
  return (
    <Fragment>
      <div className={styles.search + " search"}>
        <Form
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 14,
          }}
        ></Form>
      </div>
      <Table
        pagination={paginationProps}
        columns={columns}
        expandable={{ expandedRowRender }}
        dataSource={state.orderData}
        rowKey="orderid"
      />
      <Modal
        title="订单发货"
        open={state.isOpen}
        centered={true}
        footer={null}
        closable={false}
      >
        <Form
          name="basic"
          className={styles.Form}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          autoComplete="off"
          form={form}
        >
          <div>
            <Form.Item
              name="EMSname"
              rules={[
                {
                  required: true,
                  message: "请填写快递名称",
                },
              ]}
              label="快递名称"
            >
              <Input placeholder="快递名称" />
            </Form.Item>
            <Form.Item
              name="EMS"
              rules={[
                {
                  required: true,
                  message: "请填写快递单号",
                },
              ]}
              label="快递单号"
            >
              <Input placeholder="快递单号" />
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Input placeholder="快递单号" />
            </Form.Item>
            <Form.Item name="orderid" label="订单号">
              <Input placeholder="订单号" />
            </Form.Item>
          </div>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginRight: "10px" }}
            >
              确认
            </Button>
            <Button type="primary" htmlType="button" onClick={handleisOpen}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </Fragment>
  );
}
export default connect((state) => {
  let auth = {};
  if (state.user?.roleAuthority) {
    auth = JSON.parse(state.user.roleAuthority);
  }
  return { auth };
})(Order);
